<template>
  <div>
    <Input v-model="nickname" placeholder="您的昵称" />
    <Input v-model="messageText" placeholder="留言内容" />
    <Button @click="pushMessage">留言</Button>
    <List border item-layout="vertical" :header="messageList.length > 0 ? '评论列表' : '暂无评论'">
      <ListItem v-for="item in messageList" :key="item.messageForBlogId">
        <ListItemMeta
          avatar="https://dev-file.iviewui.com/userinfoPDvn9gKWYihR24SpgC319vXY8qniCqj4/avatar"
          :title="item.messageForBlogAuthor"
          :description="item.messageForBlogContent"
        />
        <template slot="extra">
          <Tooltip :content="item.messageForBlogDatetime | formatDate" placement="left">
              {{ item.messageForBlogDatetime | fromDate }}
            </Tooltip>
        </template>
        <template slot="action">
          <li @click="likeMessage(item.messageForBlogId)">
            <!-- @click="handleLike(item.messageForBlogId)" -->
            <Icon type="ios-thumbs-up-outline" /> {{ item.messageForBlogUp }}
          </li>
          <!-- <li @click="handleDelete(item.messageForBlogId)">
            <Tooltip transfer content="删除此评论">
              <Icon type="ios-trash-outline" />
            </Tooltip>
          </li> -->
        </template>
      </ListItem>
    </List>
  </div>
</template>

<script>
import { comment, likeMessage } from '@/api/blog.js';
export default {
  name: 'message',
  props: {
    messages: {
      type: Array,
      default: () => []
    },
    blogId: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      nickname: localStorage.getItem('nickname') || '',
      messageText: '',
      messageList: this.messages
    }
  },
  methods: {
    pushMessage() {
      if(!this.nickname) {
        this.$Message.error('昵称不能为空')
      } else if(!this.messageText) {
        this.$Message.error('评论内容不能为空')
      } else {
        comment({ id: this.blogId, nickname: this.nickname, content: this.messageText }).then(res => {
          const data = res.data
          if(res.status === 200 && data.code === 0 && data.data) {
            this.$Message.success('评论成功')
            this.messageText = ''
            localStorage.setItem('nickname', this.nickname)
            this.messageList.unshift(data.data)
          } else {
            this.$Message.error('发布失败：' + data.msg || res)
          }
        })
      }
    },
    likeMessage(id) {
      console.log('点赞')
      likeMessage(id).then(res => {
        if(res.status === 200 && res.data.code === 0) {
          this.$Message.success('点赞成功')
          const len = this.messageList.length
          for (let i = 0; i < len; i++) {
            if(this.messageList[i].messageForBlogId === id) {
              this.messageList[i].messageForBlogUp++
              return
            }
          }
        } else {
          this.$Message.error('点赞失败：' + res.data.msg || res)
        }
      })
    }
  },
}
</script>

<style>

</style>